<?php

declare(strict_types=1);

namespace app\model;
use app\common\facade\auth\Auth;
use app\common\service\auth\AuthAdminService;
use app\common\service\auth\AuthAgentService;
use app\common\service\auth\AuthApiService;
use app\common\service\order\CouponOrderService;
use app\model\base\BaseCouponBrandModel;
use think\Collection;
use think\db\BaseQuery;
use think\model\concern\SoftDelete;


/**
 * 
 *
 * @mixin \think\Model
 * @property int $id
 * @property string $name 品牌名
 * @property string $image_url 品牌logo
 * @property string $cate_id 分类
 * @property int $status 状态(1:启用,0:关闭)
 * @property string $created_at
 * @property string $updated_at
 * @property string $mark 第一次导入聚推客使用匹配，上线后可删除
 * @property int $sort 排序
 * @property-read \app\model\CouponCate[] $coupon_cate
 * @property-read \app\model\CouponProduct[] $product
 * @property float $discount_logo 折扣标识
 * @property string $deleted_at 删除时间,删除标识
 * @property-read \app\model\CouponBrandType $brand_type
 * @property-read \app\model\CouponProductChannel[] $brand_product_channel
 * @property-read \app\model\CouponProductChannel[] $product_channel
 * @property-read \app\model\CouponProductChannel[] $brandProductChannel
 * @property-read \app\model\CouponBrandType $brandType
 * @property string $subtitle 副标题
 * @property int $act_id 活动id
 * @property string $act_name 原始名称
 * @property string $belong 所属
 * @property string $type 类型比如Food、Travel
 * @property string $serv_type 服务类型id
 * @property string $subtitle_type 副标题类型
 * @property string $icon 权益模板图标
 * @property mixed $ext_data 扩展信息
 * @property string $productChannel 产品
 * productChannel
 * @property-read bool|string $sale_price_discount
 * @property string $old_image 备份图片
 * @property-read \app\model\CouponExtension $coupon_extension
 * @property-read mixed $serv_type_name
 * @method static \think\db\Query onlyTrashed()
 * @method static \think\db\Query withTrashed()
 */
class CouponBrand extends BaseCouponBrandModel
{

    use SoftDelete;

    // 设置json类型字段
    protected $json = ['ext_data'];

    // 设置JSON数据返回数组
    protected $jsonAssoc = true;

    const STATUS_ACTIVE = 1; //激活
    const STATUS_CLOSE = 0; //关闭

    //所属平台
    const BELONG_JUTUIKE = 'jutuike';
    const BELONG_HUICHONG = 'huiChong';

    //类别
    const TYPE_TRAVEL = 'travel';
    const TYPE_UNION_FOOD = 'union_food';

    //副标题类型
    const SUBTITLE_TYPE_ZK = 1;
    const SUBTITLE_TYPE_ZDY = 2;

    public $productChannelObj;




    //品牌列表
    public static function brandList($params){
        $key = !empty($params['keyword'])?$params['keyword']:($params['key'] ?? '');
        $status = $params['status'] ?? '';
        $cateId = $params['cate_id'] ?? '';
        $belong = $params['belong'] ?? '';
        $belong_origin = $params['belong'] ?? '';
        $serv_type = $params['serv_type'] ?? '';
        $brand_ids = $params['brand_ids'] ?? '';
        $extension_type = $params['extension_type'] ?? '';
        $brand_ids_arr = array();

        if ($belong == 'activity'){
            $belong = 'jutuike';//代理端避免上游暴露
        }
        if ($brand_ids) {
            $brand_ids_arr = '('. implode(',',$brand_ids) .')';
        }
        $list = self::when($key, function ($query) use ($key) {
                 $query->where('name|id', 'like','%'.trim($key).'%');
        })->when($status != '', function ($query) use ($status) {
                 $query->where('status', '=',  $status);
        })->when($cateId,function($query) use ($cateId){
                    $query->join('coupon_brand_cate_relation b', 'coupon_brand.id = b.brand_id',"left")->where("b.cate_id",$cateId);
        })->when($belong, function ($query) use ($belong) {
            if(in_array($belong, [self::BELONG_JUTUIKE, self::BELONG_HUICHONG])) {
                $query->where('belong',$belong);
            }
        })->when(Auth::from() == FROM_APP_AGENT,function ($query)use($extension_type,$belong_origin){
            $type = CouponExtension::TYPE_BRAND;
            if ($belong_origin == 'activity'){
                $type = CouponExtension::TYPE_CPS;
            }
            $getAlready =(new CouponExtension)->getAlready($type);
              $query->where('status',CouponBrand::STATUS_ACTIVE);
              if ($extension_type){
                  if ($extension_type == CouponExtension::EXTENSION_TYPE_YES){
                      $query->whereIn('id',$getAlready);
                  }else{
                      $query->whereNotIn('id',$getAlready);
                  }
              }
            })
            ->when($serv_type, function ($query) use ($brand_ids_arr){
            if (!empty($brand_ids_arr)) {
                $query->whereRaw("(belong = '".self::BELONG_HUICHONG."' and id in ".$brand_ids_arr.") or  (belong = '".self::BELONG_JUTUIKE."' and serv_type >0)");
            } else {
                $query->whereRaw("belong = '".self::BELONG_HUICHONG."' or  (belong = '".self::BELONG_JUTUIKE."' and serv_type >0)");
            }
        })->with(['coupon_cate','couponExtension'])
        ->withCount('productChannel')
        ->order('status desc, created_at desc')
        ->paginate()
        ->toArray();
        foreach ($list['data'] as $key => &$nv){
            $cate = [];
            foreach ($nv['coupon_cate'] as $k => $v){
                $cate[] = $v['name'];
            }
            $nv['coupon_cate'] = implode(",",$cate);
        }
        return $list;
    }

    public function couponCate(){
//        if (Auth::from() == FROM_APP_AGENT){
//            return $this->belongsToMany(CouponCate::class,'coupon_brand_cate_relation','cate_id','brand_id')->where('status',CouponCate::STATUS_ACTIVE);
//        }
        return $this->belongsToMany(CouponCate::class,'coupon_brand_cate_relation','cate_id','brand_id');
    }

    public function product(){
          return $this->hasMany(CouponProduct::class,"brand_id","id");
    }

    public function brandSelect()
    {
        $data = self::query()->where('name', '<>', '')->column("name", "id");
        return success('操作成功', $data);
    }

    public function brandType()
    {
        return $this->hasMany(CouponBrandType::class, 'brand_id', 'id');
    }

    public function productChannel(){
        return $this->hasMany(CouponProductChannel::class,"brand_id","id");
    }

    public function couponExtension(){
        return $this->hasOne(CouponExtension::class,'obj_id','id')->whereIn('type',[CouponExtension::TYPE_BRAND,CouponExtension::TYPE_CPS])->where('agent_id',Auth::agentId());
    }

    /**
     * 修改品牌
     * */
    public static function saveBrand($data,$scene){
        $validate = new \app\admin\validate\Coupon\Brand();
        $result = $validate->scene($scene)->check($data);
        if(!$result) return fail($validate->getError());
        $brand = self::where("id",$data['id'])->find();
        if(empty($brand)) return fail('品牌编号错误！');
        self::update($data);
        //涉及到聚推客活动的保存，清除缓存，重新建立缓存
        if (isset($data['serv_type']) && !empty($data['serv_type'])) {
            $cache_key = 'showBrandByJumpTypeService_showBrandByJumpType_getBrand_'.$data['serv_type'];
            cache($cache_key, NULL);
        }
        return success("修改成功！");
    }
    /**
     * 判断品牌是否存在或者被删除
     * */
    public function checkExists($id): bool
    {
        $info = self::findOrEmpty($id);
        if ($info->isEmpty()) {
            return false;
        }
        return true;
    }

    public function selectlinkageBrandType($brand_id)
    {
        return CouponBrandType::where('brand_id', $brand_id)
            ->where('status', 1)
            ->column('name', 'id');
    }

    public function brandProductChannel()
    {
        return $this->hasMany(CouponProductChannel::class, 'brand_id', 'id');
    }

    /**
     * 查询全局溢价默认模板
     * @param array $params
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function getDefaultTempList($params)
    {
        $brand_name = $params['brand_name']??'';
        $keyWord = $params['keyWord']??'';
        $cate_id = $params['cate_id']??'';
        $config_type = $params['config_type']??'';
        $agent_id = $params['agent_id']??0;
        $is_agent = $params['is_agent']??0;
        //全局溢价1，单个溢价2，以及全部''或者null
        $premium_type = $params['premium_type'] ?? '';
        $premiumRate = $params['premiumRate'] ?? [];
        if (empty($keyWord)){
            $keyWord = $params['key']??'';
        }
        //兼容推广
        $extension_type = $params['extension_type']??'';

        if (in_array($extension_type,[1,2]) ){
            if ($extension_type == 1){
                $extension_type = CouponExtension::EXTENSION_TYPE_YES;
            }
            if ($extension_type == 2){
                $extension_type =  CouponExtension::EXTENSION_TYPE_NO;
            }
        }


        $cat_brand_id_relations = [];

        if ($cate_id){
            $cat_brand_id_relations = CouponBrandCateRelation::query()
                ->where('cate_id',$cate_id)
                ->column('brand_id');
        }


        //查询有进行设置单个溢价的产品
        $channel_is = [];
        if (in_array($premium_type, [CouponConfig::PREMIUM_TYPE_QJ, CouponConfig::PREMIUM_TYPE_DG])) {
            $channel_is = CouponConfig::query()->where('agent_id',$agent_id)
                ->where('config_type',$config_type)
                ->where('status', CouponConfig::STATUS_ACTIVE)
                ->column('quote_id');
        }
        $brand_ids = self::where('coupon_brand.status', self::STATUS_ACTIVE)->hasWhere('brandProductChannel', function($query) use ($keyWord, $channel_is, $premium_type,$extension_type,$cat_brand_id_relations) {
            $query->availableSale()
                ->when($keyWord, function ($query) use ($keyWord) {
                    $query->where('CouponProductChannel.name|CouponProductChannel.id', 'like','%'.trim($keyWord).'%');
                })
                ->when($cat_brand_id_relations,function ($query)use($cat_brand_id_relations){
                    $query->whereIn('coupon_brand.id',$cat_brand_id_relations);
                })
                ->when($channel_is !='' , function ($query) use ($channel_is, $premium_type,$extension_type) {

                    if (in_array($premium_type,[CouponConfig::PREMIUM_TYPE_QJ, CouponConfig::PREMIUM_TYPE_DG])) {
                        if ($premium_type == CouponConfig::PREMIUM_TYPE_QJ) { //全局溢价
                            $query->whereNotIn('CouponProductChannel.id',$channel_is);
                        } else { //单个溢价
                            $query->whereIn('CouponProductChannel.id',$channel_is);
                        }
                    }

                })
            ->when($extension_type , function ($query)use($extension_type){
                //是否推广筛选
                $extensionId = (new CouponExtension)->getAlready(CouponExtension::TYPE_PRODUCT);
                if ($extension_type == CouponExtension::EXTENSION_TYPE_YES){
                    if ($extensionId){
                        $query->whereIn('CouponProductChannel.product_id',$extensionId);
                    }else{
                        $query->whereIn('CouponProductChannel.product_id',[-1]);
                    }
                }else{
                    $query->whereNotIn('CouponProductChannel.product_id',$extensionId);
                }

            });
        })->column('coupon_brand.id');

        //查询溢价配置中的channel_id
        return self::where('status', self::STATUS_ACTIVE)
            ->whereIn('id',$brand_ids)
            ->when($brand_name, function ($query) use ($brand_name) {
                $query->where('name', 'like','%'.trim($brand_name).'%');
            })->with(['brandProductChannel' => function($query) use ($keyWord, $config_type, $channel_is, $premium_type, $agent_id){
                    $query->availableSale()
                    ->when($keyWord, function ($query) use ($keyWord) {
                        $query->where('name|id', 'like','%'.trim($keyWord).'%');
                    })
                    ->when($channel_is !='', function ($query) use ($channel_is, $premium_type) {
                        if (in_array($premium_type, [CouponConfig::PREMIUM_TYPE_QJ, CouponConfig::PREMIUM_TYPE_DG])) {
                            if ($premium_type == CouponConfig::PREMIUM_TYPE_QJ) { //全局
                                $query->whereNotIn('id',$channel_is);
                            } else { //单个
                                $query->whereIn('id',$channel_is);
                            }
                        }
                    })
//                ->field('id, name, image, supplier_id, origin_id, product_id, sale_price, updated_at
//                cost_price, market_price, brand_id, sku_type, shelf_state, status, relate_state, butt')
                ->with(['base_supplier' => function($query) {
                    $query->where('serv_type', PRODUCT_COUPON_SERV);
                },'coupon_config' => function($query) use ($config_type, $agent_id) {
                    $query->where('agent_id', $agent_id)
                        ->where('config_type', $config_type)
                        ->withField('id, quote_id, value as premium_rate, updated_at, status');
                },'couponExtension']);
            },'couponExtension','couponCate'])->paginate()->each(function (CouponBrand $couponBrand) use ($agent_id, $is_agent, $premiumRate) {
                if (!($brandProductChannels = $couponBrand->brandProductChannel)->isEmpty()) {
                    $brandProductChannels->each(function (CouponProductChannel $couponProductChannel) use ($agent_id, $is_agent, $premiumRate){
                        //参数赋值
                        $couponProductChannel->agent_id = $agent_id;
                        $couponProductChannel->is_agent = $is_agent;
                        $couponProductChannel->premiumRate = $premiumRate;
                        if ($is_agent) {
                            $couponProductChannel->append(['sale_price_text','cost_price_text', 'const_premium_rate']);
                        } else {
                            $couponProductChannel->append(['sale_price_text', 'const_premium_rate']);
                        }
                    });
                }
            })->toArray();
    }

    /**
     * 根据品牌id查询品牌信息、充值类型、面额
     * @param integer $brand_id 品牌id
     * @param integer $agent_id 代理id
     * @return array
     */
    public function getProductChannlDetail(int $brand_id, int $agent_id)
    {
        $productChannelsDetail = [];
        //查询有具体产品的品牌id
        $productChannel = CouponProductChannel::query()
            ->availableSale()
            ->where('brand_id', $brand_id)
//            ->where('type', '<>', CouponProductChannel::TYPE_JTK)
            ->select();
        $query = collect($productChannel);
        $product_ids = array_unique($query->column('product_id'));
        $list = self::where('status', CouponBrand::STATUS_ACTIVE)
            ->where('id', $brand_id)
            ->field('id, name as brand_name, image_url, discount_logo')
            ->with(['brandType' => function($query) use ($brand_id,  $agent_id,  $product_ids) {
                $query->where('status', CouponBrandType::STATUS_ACTIVE)
                    ->field('id, brand_id, name as brandTypeName, sort')
                    ->order('sort desc, updated_at desc')
                ->with(['product' => function($query) use($brand_id,  $agent_id,  $product_ids){
                    $query->where('status', CouponProduct::STATUS_ACTIVE)
                        ->where('type',CouponProduct::TYPE_QY)
                        ->whereIn('id', $product_ids)
                        ->field('id, name as productName, type_id')
                        ->order('sort desc, updated_at desc')
                        ->with(['couponProductChannel' => function($query) use($brand_id, $agent_id) {
                            /** @var BaseQuery $query */
                            $query->availableSale()
                                ->where('brand_id', $brand_id)
//                                ->where('type', '<>', CouponProductChannel::TYPE_JTK)
                                ->order('cost_price asc')
                                ->field('id, name, supplier_id, origin_id, product_id, cost_price, market_price, brand_id, rule, extend')
                                ->withLimit(1);//取最便宜的一个产品
                        }]);
                }]);
            }])->select()->each(function(CouponBrand $couponBrand) use ($agent_id){
                if (!($brandType = $couponBrand->brandType)->isEmpty()) {
                    $brandType->each(function(CouponBrandType $brandType) use ($agent_id){
                        if (!($product = $brandType->product)->isEmpty()) {
                            $product->each(function(CouponProduct $couponProduct) use ($agent_id){
                                if (!($couponProductChannel = $couponProduct->couponProductChannel)->isEmpty()) {
                                    $couponProductChannel->each(function(CouponProductChannel $couponProductChannel) use ($agent_id) {
                                        $couponProductChannel->agent_id = $agent_id;
                                        if ($agent_id) {
                                            //代理端
                                            $couponProductChannel->is_agent = 1;
                                        }
                                        $couponProductChannel->append(['sale_price_text', 'share_profit_save', 'buy_input_rule']);
                                    });
                                }
                            });
                        }
                    });
                }
            })->toArray();

        if (!empty($list)) {
            $productChannelsDetail = $list[0];
            foreach ($productChannelsDetail['brandType'] as $key => $brandType) {
                if (empty($brandType['product'])) {
                    unset($productChannelsDetail['brandType'][$key]);
                }
                foreach ($brandType['product'] as $product) {
                    if (empty($product['couponProductChannel'])) {
                        unset($productChannelsDetail['brandType'][$key]);
                    }
                }
            }
            $brandType = array_values($productChannelsDetail['brandType']);
            $productChannelsDetail['brandType'] = $brandType;
        }
        return $productChannelsDetail;
    }

    //获取商品详情页面---暂未使用
    public function getProductChannlDetailNew(int $brand_id){
        $list = CouponProductChannel::query()
            ->where('status', CouponProductChannel::STATUS_ACTIVE)
            ->where('brand_id', $brand_id)
            ->where('type', '<>', CouponProductChannel::TYPE_JTK)
            ->where('butt', CouponProductChannel::BUTT_ACTIVE)
            ->where('sku_type', CouponProductChannel::SKU_TYPE_ZC)
            ->where('shelf_state', CouponProductChannel::RELETE_STATE_YPP)
            ->order('cost_price asc')
            ->group('product_id')
            ->append(['sale_price_text'])
            ->field('id, name, supplier_id, origin_id, product_id, cost_price, market_price, brand_id, rule')
            ->with(['product' => function($query){
                $query->where('status', CouponProduct::STATUS_ACTIVE)
                    ->where('type',CouponProduct::TYPE_QY)
                    ->field('id, name as productName,type_id')
                    ->order('sort desc, updated_at desc')->with(['couponBrandType' =>function($query){
                        $query->where('status', CouponBrandType::STATUS_ACTIVE)
                            ->field('id, brand_id, name as brandTypeName, sort')
                            ->order('sort desc, updated_at desc')
                            ->with(['brand'=>function($query) {
                                $query->where('status', CouponBrand::STATUS_ACTIVE)
                                    ->field('id, name as brand_name, image_url, discount_logo');
                            }] );
                    }]);
            }])->select()->toArray();
        //return $list;
        $data = array();
        //组装品牌brand
        $data['id'] = $list[0]['product']['couponBrandType']['brand']['id'];
        $data['brand_name'] = $list[0]['product']['couponBrandType']['brand']['brand_name'];
        $data['image_url'] = $list[0]['product']['couponBrandType']['brand']['image_url'];
        $data['discount_logo'] = $list[0]['product']['couponBrandType']['brand']['discount_logo'];
        foreach ($list as $key => $value) {
            //组装面额product
//            $data['brandType'][$key]['product']['id'] = $value['product']['id'];
//            $data['brandType'][$key]['product']['productName'] = $value['product']['productName'];
//            $data['brandType'][$key]['product']['type_id'] = $value['product']['type_id'];
            //组装产品couponProductChannel
//            $data['brandType'][$key]['product']['couponProductChannel']['id'] = $value['id'];
//            $data['brandType'][$key]['product']['couponProductChannel']['name'] = $value['name'];
//            $data['brandType'][$key]['product']['couponProductChannel']['supplier_id'] = $value['supplier_id'];
//            $data['brandType'][$key]['product']['couponProductChannel']['origin_id'] = $value['origin_id'];
//            $data['brandType'][$key]['product']['couponProductChannel']['product_id'] = $value['product_id'];
//            $data['brandType'][$key]['product']['couponProductChannel']['cost_price'] = $value['cost_price'];
//            $data['brandType'][$key]['product']['couponProductChannel']['market_price'] = $value['market_price'];
//            $data['brandType'][$key]['product']['couponProductChannel']['brand_id'] = $value['brand_id'];
//            $data['brandType'][$key]['product']['couponProductChannel']['rule'] = $value['rule'];
//            $data['brandType'][$key]['product']['couponProductChannel']['sale_price_text'] = $value['sale_price_text'];
            $temp = [
                'id'                =>  $value['id'],
                'name'              =>  $value['name'],
                'supplier_id'       =>  $value['supplier_id'],
                'origin_id'         =>  $value['origin_id'],
                'product_id'        =>  $value['product_id'],
                'cost_price'        =>  $value['cost_price'],
                'sale_price_text'   =>  $value['sale_price_text'],
                'market_price'      =>  $value['market_price'],
                'brand_id'          =>  $value['brand_id'],
                'rule'              =>  $value['rule'],
            ];
            $tmp  = [
                'id'          =>  $value['product']['id'],
                'productName' =>  $value['product']['productName'],
                'type_id'     =>  $value['product']['type_id'],
                'couponProductChannel' => $temp,
            ];
            if (!empty($data['brandType'])) {
                foreach ($data['brandType'] as $k => $brandType) {
                    if ($value['product']['couponBrandType']['id'] == $brandType['id']) {
                        $data['brandType'][$k]['product'][] = $tmp;
                        continue 2;
                    }
                }
            }
            //组装充值类型brandType
            $data['brandType'][$key]['id'] = $value['product']['couponBrandType']['id'];
            $data['brandType'][$key]['brand_id'] = $value['product']['couponBrandType']['brand_id'];
            $data['brandType'][$key]['brandTypeName'] = $value['product']['couponBrandType']['brandTypeName'];
            $data['brandType'][$key]['sort'] = $value['product']['couponBrandType']['sort'];
            $data['brandType'][$key]['product'][] = $tmp;
        }
        $data['brandType'] = array_values($data['brandType']);
        return $data;
    }

    //品牌名称搜索
    public function searchAgentNameAttr($query, $value, $params)
    {
        $query->where('name','like', $value . '%');
    }

    /**
     * 根据条件获取聚推客活动列表
     */
    public function getJutuikelList($params)
    {
        return self::query()->where('belong', self::BELONG_JUTUIKE)
            ->withSearch(['type', 'act_id', 'name', 'serv_type', 'status'], $params)
            ->field($params['field'])
            ->select();
    }

    /**
     * 类别筛选
     */
    public function searchTypeAttr($query, $value, $params)
    {
        $type = $params['type'] ?? '';

        if (!empty($type)) {
            $query->where('type', $type);
        }

    }

    /**
     * act_id筛选
     */
    public function searchActIdAttr($query, $value, $params)
    {
        $act_id = $params['act_id'] ?? '';

        if (!empty($act_id)) {
            $query->where('act_id', $act_id);
        }
    }

    /**
     * 系统品牌名称筛选
     */
    public function searchNameAttr($query, $value, $params)
    {
        $name = $params['name'] ?? '';

        if (!empty($short_name)) {
            $query->where('name', 'like', '%'.trim($name).'%');
        }
    }

    /**
     * 服务类别筛选
     */
    public function searchServTypeAttr($query, $value, $params)
    {
        $serv_type = $params['serv_type'] ?? '';

        if (!empty($serv_type)) {
            $query->where('serv_type', $serv_type);
        }
    }

    /**
     * 状态筛选
     */
    public function searchStatusAttr($query, $value, $params)
    {
        $status = $params['status'] ?? '';

        if (!empty($status)) {
            $query->where('status', $status);
        }
    }

    /**
     * 状态所属
     */
    public function searchBelongAttr($query, $value, $params)
    {
        /*$source = $params['source']??'';
        if ($source != 'icon') {
            $belong = $params['belong'] ?? self::BELONG_HUICHONG;
            if (!empty($belong)) {
                $query->where('belong', $belong);
            }
        }*/
        $belong = $params['belong']??'';
        if (!empty($belong)) {
            $query->where('belong', $belong);
        }
    }

    /**
     * 服务
     * @param $value
     */
    public function getServTypeNameAttr($value){

        if (request()->pathinfo() == 'stat.order/reportForm'){
            if (empty(PRODUCT_SERV_TYPE[$this->serv_type]['name'])){
                return '权益';
            }
        }

        if (empty(PRODUCT_SERV_TYPE[$this->serv_type]['name'])){
            return '未知';
        }
        return PRODUCT_SERV_TYPE[$this->serv_type]['name'];
    }

    /**
     * 获取溢价后的销售价
     * @param $value
     * @param $model
     * @return false|string
     */
    public function getSalePriceDiscountAttr($value, $model)
    {
        $agent_id = Auth::agentId();
        $service = new CouponOrderService();
        $arr = array();
        //因为产品的市场价和销售价相对来说比较少变化，考虑加缓存
        /**
         * @var Collection $productChannels
         */
        $productChannels = $this->productChannelObj;

        if ($productChannels) {
            $productChannels->each(function (CouponProductChannel $couponProductChannel) use ($service, &$arr, $agent_id){

                $result = $service->calculateThePrice($couponProductChannel, $agent_id);
                //市场价
                $market_price = $couponProductChannel->market_price;

                //经过代理溢价后的销售价
                $sale_price = (float)$result->getPayAmount(); //支付价格(加上代理溢价后的价格)

                //计算折扣
                $discount = (float)bcdiv((string)$sale_price, (string)$market_price, 3);

                $discount = round($discount ,2);

                $length  = getDecimalLen($discount);

                if ($length == 1) {
                    //刚好是整数的话，不保留小数
                    $discount = bcmul((string)$discount, '10');
                } else {
                    //保留一位小数
                    $discount = bcmul((string)$discount, '10',1);
                }

                array_push($arr, $discount);
            });
        }
        return current(bubble_sort($arr)).'折起';

        //$agent_id = Auth::agentId();
        //$service = new CouponOrderService();
        //$brandMode = new CouponBrand();
        //$arr = array();
        //$rows = $brandMode->getProductChannlDetail($this->id, $agent_id);
        //因为产品的市场价和销售价相对来说比较少变化，考虑加缓存
//        if (isset($rows['brandType']) && !empty($brandType = $rows['brandType'])) {
//            foreach ($brandType as $brand) {
//                if (isset($brand['product']) && !empty($brand['product'])) {
//                    foreach ($brand['product'] as $product) {
//                        $couponProductChannel = $product['couponProductChannel'][0];
//
//                        $result = $service->calculateThePrice($couponProductChannel['id'], $agent_id);
//
//                        //市场价
//                        $market_price = $couponProductChannel['market_price'];
//
//                        //经过代理溢价后的销售价
//                        $sale_price = (float)$result->getPayAmount(); //支付价格(加上代理溢价后的价格)
//
//                        //计算折扣
//                        $discount = (float)bcdiv((string)$sale_price, (string)$market_price, 3);
//
//                        $discount = round($discount ,2);
//
//                        $length  = getDecimalLen($discount);
//
//                        if ($length == 1) {
//                            //刚好是整数的话，不保留小数
//                            $discount = bcmul((string)$discount, '10');
//                        } else {
//                            //保留一位小数
//                            $discount = bcmul((string)$discount, '10',1);
//                        }
//
//                        array_push($arr, $discount);
//
//                        //array_push($arr, $market_price.'|'.$sale_price.'|'.$discount.'|'.$length,1);
//                    }
//                }
//            }
//            return current(bubble_sort($arr)).'折起';
//        }
    }
}
